package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public Result select() {
        String listKey = "list:shop:type";
        List<ShopType> types = (List<ShopType>) redisTemplate.opsForList().index(listKey, 0);
        // 先要判断缓存中是否有值
        // 存在 直接返回
        if (types != null){
            return Result.ok(types);
        }
        // 不存在，查询数据
        List<ShopType> shopTypes = this.query().orderByAsc("sort").list();
        // 写入redis缓存
        redisTemplate.opsForList().rightPush(listKey, shopTypes);
        redisTemplate.expire(listKey,30L, TimeUnit.MINUTES);
        return Result.ok(shopTypes);
    }
}
